<?php
/**
* @package care_api
*/
/**
*/
require_once($root_path.'include/care_api_classes/class_core.php');
require_once($root_path.'include/care_api_classes/class_person.php');
/**
*  Person methods. 
*
* Note this class should be instantiated only after a "$db" adodb  connector object  has been established by an adodb instance
* @author Astrid Paravisini
* @author Aixbel Martinez
* @version beta 2.0.1
* @package care_api
*/
class GuiHistory extends Core {

  var $auditor = false;

        # Language tables
	var $langfiles= array('history.php', 'interconsulta.php');
        # tables
        var $tb_guihistory='care_historia_especificacion_de_campos';
        var $tb_historydata='care_historia_datos_historia_clinica';
        var $tb_soap='care_historia_soap';
        var $tb_adjunto='care_historia_adjuntos';
	/**
	* Sql query result buffer
	* @var adodb record object
	*/
	var $result;
	/**
	* Universal flag
	* @var boolean

	*
	*
	*
	*
	*/
	
	var $ok;
	/**
	* Universal buffer
	* @var mixed
	*/
	var $buffer;
	/**
	* Returned row buffer
	* @var array
	*/
	var $row;
        /**
	* Object(s) to fetch
	* @var string
	*/
	var $ficha;
        var $subficha;
        var $pid;
        var $correlativo;
	/**
	* Returned historia data buffer
	* @var array
	*/
        var $filtrarCampo = array("examen_fisico", "soap", "laboratorio");
	var $historia=array();
        var $data_array=array('id_campo', 'valor', 'id_paciente', 'id_correlativo', 'ficha');
        var $soap = array('fecha', 'nombre_medico', 'matricula_medico', 'id_paciente', 'clasificacion_medico', 'subjetivo', 'objetivo', 'apreciacion', 'planTPR', 'tratamiento', 'tipo', 'referido');

	var $last_id;
	/**
	* Constructor
	* @param int ID number
	*/
	function GuiHistory ($ficha) {
	        $this->ficha=$ficha;

		global $db;
		global $_SESSION;

		//$sql='SELECT name, login_id, password, permission, lockflag FROM care_users WHERE login_id=\''.addslashes($_SESSION['sess_login_userid']).'\'';

                /*if($ergebnis=$db->Execute($sql))
		  {
		    $zeile=$ergebnis->FetchRow();
		    
		    if (($zeile['permission'] == '_a_3_historiaauditor')||($zeile['permission'] == 'System_Admin'))
		      {
			$this->auditor = true;
		      } 
		    else 
		      {
			$this->auditor = false;
		      }
		    
		  }*/
                  $ergebnis=$db->SelectUserInfo($_SESSION['sess_login_userid']);
                  if($ergebnis)
		  {
		    $zeile=$ergebnis;

		    if (($zeile['permission'] == '_a_3_historiaauditor')||($zeile['permission'] == 'System_Admin'))
		      {
			$this->auditor = true;
		      }
		    else
		      {
			$this->auditor = false;
		      }

		  }
	}
	/**
	* Sets ficha.
	* @access public
	* @param string ficha
	*/
	function setFicha($ficha) {
	    $this->ficha=$ficha;
	}
        /**
	* Sets subficha.
	* @access public
	* @param string subficha
	*/
	function setSubFicha($subficha) {
	    $this->subficha=$subficha;
	}
        /**
	* Sets pid.
	* @access public
	* @param string subficha
	*/
	function setPid($pid) {
	    $this->pid=$pid;
	}
	/**
	* Prepares the internal buffer array for insertion routine.
	* @access private
	*/
	function prepInsertArray(){
            global $_POST;

            GLOBAL $db;
            $ergebnis=$db->SelecLastIdCorr();
            $corr =$ergebnis +1;
            //echo ("correlativo ".$corr." y lo que obtuve ");
            //var_dump($zeile);
            //var_dump($ergebnis);
            $values=array();
            
            if (strcmp('soap', $this->ficha))
            {
                $this->loadCampos($this->ficha);
                while(list($k, $v)=each($_POST))
                {
                    if (in_array($k, $this->history))
                    {
                        //'id_campo', 'valor', 'id_paciente', 'id_correlativo', 'ficha'
                        //$values .= "('$k', '$v', '$this->pid', $this->correlativo, '$this->ficha'),";
                        $values[]= array ('id_campo'=>$k, 'valor'=>$v, 'id_paciente'=>$this->pid, 'id_correlativo'=>$corr, 'ficha'=>$this->ficha);
                        
                    }
                }
                //$values=substr_replace($values,'',(strlen($values))-1);
            }
            else
            {
                extract($_POST);
//                 $ff = explode("/", $fecha);
                   //$values = "('$fecha', '$nombre_medico', '$matricula_medico', $pid, '$clasificacion_medico', '$subjetivo', '$objetivo', '$apreciacion', '$planTPR', '$tratamiento', '$tipo', '$referido')";
                   $values[] = array('fecha'=>$fecha, 'nombre_medico'=>$nombre_medico, 'matricula_medico'=>$matricula_medico, 'id_paciente'=>$pid, 'clasificacion_medico'=>$clasificacion_medico, 'subjetivo'=>$subjetivo, 'objetivo'=>$objetivo, 'apreciacion'=>$apreciacion, 'planTPR'=>$planTPR, 'tratamiento'=>$tratamiento, 'tipo'=>$tipo, 'referido'=>$referido);
                
            }
            return $values;
        }
        /**
	* Prepares the internal buffer array for update routine.
	* @access private
	*/
	function prepUpdateArray(){
            global $_POST;
            global $db;

            if (strcmp('soap', $this->ficha))
            {
                $this->pid = $_POST['pid'];
                $this->ficha = $_POST['ficha'];
				$temp_corr=$this->correlativo;              
				if ($this->ficha=="antecedentes")
                {
                    
                	$temp_corr = $_POST['id_correlativo'];
                }
                
                $this->loadCampos($this->ficha);
                $fichasins = $this->loadFichasInsertadas($this->pid, $this->ficha);
                //var_dump($fichasins);
                //var_dump($this->history);
                while(list($k, $v)=each($_POST))
                {
//
//                   echo "la clave que estoy leyendo es: " . $k . "<br>";
                    if (in_array($k, $this->history) && in_array($k, $fichasins))
                    {
//                         echo "esta en el array e insertado<br>";
                        //$up[] = "UPDATE $this->tb_historydata SET valor='$v' WHERE ficha='$this->ficha' AND id_paciente='$this->pid' AND id_campo='$k' AND id_correlativo=$temp_corr;";
                        $temp=array();
                        $temp[]=array('valor'=>$v);
                        $temp[]=array('ficha'=>$this->ficha, 'id_paciente'=>$this->pid, 'id_campo'=>$k, 'id_correlativo'=>$temp_corr);
                        
                        $up[]=$temp;
                    }
                    else if (in_array($k, $this->history) && !in_array($k, $fichasins))
                    {
//                         echo "esta en el array pero NO insertado<br>";
                        //$up[] = "INSERT INTO $this->tb_historydata (id_campo, valor, id_paciente, id_correlativo, ficha) VALUES ('$k', '$v', '$this->pid', $temp_corr, '$this->ficha');";
                        $up = $db->Transact(NULL,array('id_campo'=>$k, 'valor'=>$v, 'id_paciente'=>$this->pid, 'id_correlativo'=>$temp_corr, 'ficha'=>$this->ficha),"Insert",$this->tb_historydata);
                    }
                }
            }
            else
            {
                //$acum = "UPDATE $this->tb_soap SET ";
                $acum = array();
                $fichasoap = $this->getAllSoapInfoObject($this->pid,$_POST['id']);
                $fichasoap = $fichasoap[0];
                //var_dump($fichasins);
                while(list($k, $v)=each($_POST))
                {
                    if (in_array($k, $this->soap))
                    {
                        if($fichasoap[$k]!=$v){
                            if (!strcmp($k, "fecha"))
                            {
                                //$vv = explode("/", $v);
                                //$acum .= " $k='".$vv[2]."-".$vv[1]."-".$vv[0]."',";
                                $acum[''.$k.'']=$v;

                            }
                            else
                            {
                                //$acum .= " $k='$v',";
                                $acum[''.$k.'']=$v;
                            }
                        }
                    }
                }
                //$acum=substr_replace($acum,'',(strlen($acum))-1);
                //$up[] = $acum . " WHERE id=".$_POST['id'];
                $temp[]=$acum;
                $temp[]=array('id'=>$_POST['id']);
                $up[]=$temp;
            }
//                 echo "<pre>";
//                 var_dump($up);
//                 echo "</pre>";
                return $up;
        }
	/**
	* Database transaction. Uses the adodb transaction method.
	* @access private
	*/
	function Transact($sql='') {

	    global $db;
	    //$db->debug=true;
        if(!empty($sql)) $this->sql=$sql;

        $db->BeginTrans();
        $this->ok=$db->Execute($this->sql);
        if($this->ok) {
            $db->CommitTrans();
			return true;
        } else {
	        $db->RollbackTrans();
			return false;
	    }
    }	
	/**
	* Inserts the data into the care_person table.
	* @access private
	* @param int PID number
	* @return boolean
	*/
    function insertDataFromArray($values) {
		$x='';
		$v='';
		$index='';

                if (strcmp('soap', $this->ficha))
                {
                    while(list($x, $v)=each($this->data_array)) {
                        $index.="$v,";
                    }
                    $tb = $this->tb_historydata;
                }
                else
                {
                    while(list($x, $v)=each($this->soap)) {
                        $index.="$v,";
                    }
                    $tb = $this->tb_soap;
                }
                $index=substr_replace($index,'',(strlen($index))-1);
		//$this->sql="INSERT INTO $tb ($index) VALUES $values";
                global $db;
                //echo("<br><br>");
                //print_r($values);
                //echo("<br><br>");
                foreach($values as $value){
                $x = $db->Transact("",$value,"Insert",$tb);
                }
                   // buscado array ('ficha'=>$this->ficha, 'id_paciente'=$this->pid, 'id_campo'=>$k, 'id_correlativo'=>$temp_corr )
                   // valores nuevos array ('valor'=>'$v',)

                   //var_dump($this);
                   //echo ($this);


		//$x = $this->Transact("","Insert",$tb);
		
		$this->last_id = $db->LastInserted();

		return $x;
	}

	/**
	* Inserts the data from the internal buffer array into the care_person table.
	*
	* The data must be packed in the buffer array with index keys as outlined in the <var>$elems_array</var> array.
	* @access public
	* @return boolean
	*/
	function insertDataFromInternalArray() {
            global $_POST, $db;
            extract($_POST);
            $this->setPid($pid);
            $this->setFicha($ficha);

            if (strcmp('soap', $this->ficha))
            {
                /*$this->sql="CALL p_getCorrelativo(@numero)";
                $t=$this->Transact();
                */
                $t=$db->CallProcedure('p_getCorrelativo','@numero');
                if ($t)
                {
                    /*$this->sql="SELECT @numero";
                    $this->result=$db->Execute($this->sql);
                    $tmp = $this->result->FetchRow();*/
                    $tmp=$db->SelectProcedureResult('@numero');
                }
                $this->correlativo = $tmp['@numero'];
//                 echo "el correlativo $this->correlativo<br>";
            }

            $values = $this->prepInsertArray();
            return $this->insertDataFromArray($values);
	}

        function updateDataFromArray() {
            global $_POST, $db;
            extract($_POST);
            $corr=$_POST['id_correlativo'];
            //var_dump($_POST);
            $this->setPid($pid);
            $this->setFicha($ficha);
			$this->correlativo=$corr;
            $ups=array();

            $ups=$this->prepUpdateArray();
            //var_dump($ups);
            /*foreach ($ups as $u)
            {
                $this->sql=$u;
                $t = $this->Transact();

            }*/
            if (strcmp('soap', $this->ficha))
                $tb=$this->tb_historydata;
            else
                $tb=$this->tb_soap;
            
            if($ups==FALSE)
                return FALSE;
            $return=FALSE;
            foreach($ups as $up){
                $x = $db->Transact($up[1],$up[0],"Update",$tb);
                $return=$return || $x;
            }
            
            return $return;
	}
        /**
	* Gets all guihistory information based on its ficha.
	*
	* The returned adodb record object contains a row or array.
	* This array contains data with the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - addr_citytown_name = name of the city or town
	*
	* @access public
	* @param int ID number
	* @return mixed adodb object or boolean
	*/
	function getAllInfoObject($ficha, $pid, $corr = 0) {
	    global $db;
            
            /*$sel = '';
            $join = '';
            $and = '';

            if ($corr != 0)
            {
                $sel = ", d.valor ";
                $join = " LEFT JOIN $this->tb_historydata d ON (h.nombre = d.id_campo) ";
                $and = " AND d.id_correlativo = $corr";
            }

            $this->sql="SELECT h.*$sel FROM $this->tb_guihistory h $join WHERE h.ficha='$ficha' $and ORDER BY h.orden";
	    //system("logger -t sinapsis " . $this->sql);
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			} else { return false; }
		} else { return false; }
            */
            /* HAY Q TERMINAR ESTO*/
            $sel = array('h.*');
            $join = ''.$this->tb_guihistory.' h';
            $where = array('h.ficha'=>$ficha);
            $order="h.orden";
             if ($corr != 0)
             {
                 $sel[]='d.valor';
                 $join.=" LEFT JOIN $this->tb_historydata d ON (h.nombre = d.id_campo) ";
                 $where['d.id_correlativo']= $corr;
             }
             $salida=$db->GuiSelect($sel,$where,$join,$order);
             if($salida) {
                return $salida;

		} else { return false; }
             
                
	}

        function getAllSoapInfoObject($pid, $id = 0) {
	    global $db;
            /*
            $sel = "id, fecha";
            $and = " id_paciente=$pid ";

            //estoy consultando
            if ($id != 0)
            {
                $sel ="*";
                $and = " id = $id";
            }

            $this->sql="SELECT $sel FROM $this->tb_soap WHERE $and";
//            echo $this->sql;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			} else { return false; }
		} else { return false; }
          
                */
            $sel = array('id', 'fecha');
            $where = array('id_paciente'=>$pid);

            //estoy consultando
            if ($id != 0)
            {
                $sel =array('*');
                $where = array('id'=>$id);
            }

            //$this->sql="SELECT $sel FROM $this->tb_soap WHERE $and";
            //echo $this->sql;
            $salida=$db->GuiSelect($sel,$where,$this->tb_soap,$order);
        if($salida) {

            return $salida;


	} else { return false; }

	}
        /**
	* Gets all historydata information based on its ficha, id_paciente and correlativo.
	*
	* The returned adodb record object contains a row or array.
	* This array contains data with the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - addr_citytown_name = name of the city or town
	*
	* @access public
	* @param int ID number
	* @return mixed adodb object or boolean
	*/
	function getAllDataObject($ficha, $pid) {
	    global $db;
            /*
            if (strcmp($ficha, "inmunizaciones")){
                $sel = " DISTINCT ";
                $where = '';

                if (in_array($ficha, $this->filtrarCampo))
                {
                    $sel = '';
                    $where = " AND id_campo='fecha'";
                }

                $this->sql="SELECT $sel valor as fecha, id_paciente, id_correlativo, ficha FROM $this->tb_historydata WHERE ficha='$ficha' AND id_paciente='$pid' $where ORDER BY id_correlativo";
            }
            else
            {
                //$this->sql="SELECT id_campo, valor as fecha, id_paciente, id_correlativo, ficha FROM $this->tb_historydata WHERE ficha='$ficha' AND id_paciente='$pid' AND valor != '' ORDER BY valor";
                $this->sql="SELECT g.nombre AS id_campo, h.valor AS fecha, h.id_paciente, h.id_correlativo, h.ficha FROM $this->tb_guihistory g LEFT JOIN $this->tb_historydata h ON (g.nombre = h.id_campo) WHERE g.ficha='$ficha' and id_paciente='$pid' ORDER BY g.orden, g.nombre, h.valor ASC";
            }
//             echo $this->sql;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			} else { return false; }
		} else { return false; }
                */
                
                if (strcmp($ficha, "inmunizaciones")){
                $sel = array(" DISTINCT ");
                $where = array();

                if (in_array($ficha, $this->filtrarCampo))
                {
                    $sel = array(" ");
                    $where = array('id_campo'=>'fecha');
                }

                //$this->sql="SELECT $sel valor as fecha, id_paciente, id_correlativo, ficha FROM $this->tb_historydata WHERE ficha='$ficha' AND id_paciente='$pid' AND valor != '' $where ORDER BY id_correlativo";
                var_dump($sel);
                $sel[0]=$sel[0]."valor as fecha";
                $sel[]="id_paciente";
                $sel[]="id_correlativo";
                $sel[]="ficha";
                $where['ficha']=$ficha;
                $where['id_paciente']=$pid;
                $order="id_correlativo";
                $table=$this->tb_historydata;

            }
            else
            {
                
                
                $sel=array("g.nombre AS id_campo", "h.valor AS fecha", "h.id_paciente", "h.ficha", "h.id_correlativo"  );
                $table="$this->tb_guihistory g LEFT JOIN $this->tb_historydata h ON (g.nombre = h.id_campo)";
                $where=array('g.ficha'=>$ficha, 'id_paciente'=>$pid);
                $order="g.orden, g.nombre, h.valor ASC";
            }
//             echo $this->sql;
        $salida=$db->GuiSelect($sel,$where,$table,$order);
        if($salida) {
            
            return $salida;
	
	} else { return false; }
	}
        /**
	* Gets all guihistory information based on a subficha ficha.
	*
	* The returned adodb record object contains a row or array.
	* This array contains data with the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - addr_citytown_name = name of the city or town
	*
	* @access public
	* @param int ID number
	* @return mixed adodb object or boolean
	*/
	function getAllInfoObjectBySubficha($ficha, $subficha, $pid, $corr = 0) {
	    global $db;

            /*$sel = '';
            $join = '';
            $and = '';

//             if ((!strcmp($ficha, 'antecedentes')) || ($corr != 0))
//             {
                $sel = ", d.valor ";
                $join = " LEFT JOIN $this->tb_historydata d ON (h.nombre = d.id_campo) ";
//             }

            if ($corr != 0)
            {
                $and = " AND d.id_correlativo = $corr";
            }
            else if (!strcmp($ficha, 'antecedentes'))
            {
                $and = " AND d.id_paciente = $pid";
                $union = " UNION (SELECT h.*, '' FROM $this->tb_guihistory h WHERE h.ficha='$ficha' AND h.subficha='$subficha' AND h.nombre NOT IN (SELECT id_campo FROM $this->tb_historydata d WHERE d.id_paciente = $pid))";
            }


            $this->sql="(SELECT h.*$sel FROM $this->tb_guihistory h $join WHERE h.ficha='$ficha' AND h.subficha='$subficha' $and) $union ORDER BY orden";
            //echo $this->sql . "<br>";
            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    return $this->result;
                }
                else {
                    $this->sql="SELECT h.* FROM $this->tb_guihistory h WHERE h.ficha='$ficha' AND h.subficha='$subficha' ORDER BY h.orden";
                    //echo $this->sql . "<br>";
                    if($this->result=$db->Execute($this->sql)) {
                        if($this->result->RecordCount()) {
                            return $this->result;
                        }
                        else {
                            return false;
                        }
                    }
                }
	   }
            else { return false; }*/
            if ($corr!=0)
                $return=$db->objectBySubficha($ficha, $subficha, $pid,$this->tb_historydata,$this->tb_guihistory, $corr);
            else
                $return=$db->objectBySubficha($ficha, $subficha, $pid,$this->tb_historydata,$this->tb_guihistory);

                return $return;

        }
        
        /*
         * funcion encargada de devolver el correlativo de una subficha de un paciente, si no existe retorna falso
         * 
         * 
         * */
        
        function getCorrBySubficha($ficha, $sub, $pid){
        global $db;

            /*$sel = '';
            $join = '';
            $and = '';


                //if ((!strcmp($ficha, 'antecedentes')) || ($corr != 0))
                //{
                $sel = ", d.id_correlativo ";
                $join = " LEFT JOIN $this->tb_historydata d ON (h.nombre = d.id_campo) ";
                //}

           
            if (!strcmp($ficha, 'antecedentes'))
            {
                $and = " AND d.id_paciente = $pid AND d.id_correlativo IS NOT NULL";
                
            }


            $this->sql="(SELECT h.*$sel FROM $this->tb_guihistory h $join WHERE h.ficha='$ficha' AND h.subficha='$sub' $and) ORDER BY orden";
            echo $this->sql . "<br>";
            if($this->result=$db->Execute($this->sql)) {
				$return=$this->result;
				
            	
                return $return->fields['id_correlativo'];
                
                
                
	   }
            else { return false; }*/

            $sel = array();
            $table ='';
            $where = array();


                //if ((!strcmp($ficha, 'antecedentes')) || ($corr != 0))
                //{
                $sel []= "d.id_correlativo";
                $table = "LEFT JOIN $this->tb_historydata d ON (h.nombre = d.id_campo)";
                //}


            if (!strcmp($ficha, 'antecedentes'))
            {
                $where['d.id_paciente'] = $pid;
                $where['d.id_correlativo']='IS NOT NULL';

            }



            $sel[]="h.*";
            $tab="$this->tb_guihistory h";
            $table=$tab." ".$table;
            $where['h.ficha']=$ficha;
            $where['h.subficha']=$sub;
            $order="orden";

            if($result=$db->GuiSelect($sel,$where,$table,$order)) {



                return $result[0]['id_correlativo'];



	   }
            else { return false; }


                   	
        }
        
        
        
        
        function createOpt($temp,$calendar,$pid, $readonly = true)
        {
		//echo "<!-- CREATE OPT -->";
	  /*echo "<pre>";
               var_dump($update);
               echo "</pre>";*/
            global $lang, $root_path;
		$trup = '';
                $nombreCampo = '';
            if (strlen($temp['valor']) != 0)
            {
                $trup = '<tr><td><input name="update" type="hidden" value="1"></td></tr>';
            }

            # Load the language tables
	    $lang_tables =$this->langfiles;
            include($root_path.'include/inc_load_lang_tables.php');

	    
	    $disabled = "";
	    if (!$this->auditor) {
	      if ($temp['condicion'] != NULL) {
		if (eval($temp['condicion'])) {
		  //echo "TRUE CONDICION";
		} else {
		  //echo "FALSE CONDICION";
		  $disabled = "disabled";
		}
	      }
	    } else {
	      $readonly = false;
	    }
	      
            if ($temp['obligatorio']) 
            {
                $nombreCampo = '<font color="red">' . ${'LD' . $temp['nombre']} . '</font>';
            }
            else
            {
                if (strlen(strstr($temp['nombre'], "clasificacion")))
                {
                    $nombreCampo = $LDclasificacion;
                }
                else
                {
                    $nombreCampo = ${'LD' . $temp['nombre']};
                }
            }

            $opt = '<tr><td  class="reg_item">' . $nombreCampo . '</td><td  class="reg_input">';
                $tipos = explode('$', $temp['tipo']);
                    foreach ($tipos as $tipo)
                    {
                        $valores = explode('?', $tipo);
                        $t = $valores[0];

//                         echo "<pre>";
                         //var_dump($valores);
//                         echo "<pre>";

			if ($readonly) { $disabled = "disabled"; }
                        if (!strcmp($t, 'checkbox') || !strcmp($t, 'radio'))
                        {
                            for ($i=1;$i<count($valores);$i++)
                            {
                                if (strlen($temp['valor']) != 0)
                                {
                                    if (!strcmp($temp['valor'], $valores[$i]))
                                    {
                                        $check = 'checked';
                                    }
                                    else
                                    {
                                        $check = '';
                                    }
                                }
                                else if ($valores[$i] == "Ignorado")
                                {
                                    $check = 'checked';
                                }

                                   			
				if($valores[$i]=='Si'){	
		
                                $opt .= '<input type="' . $t . '" name="' . $temp['nombre'] . '" value="' . $valores[$i] . '"' . $check .' ' . $disabled . '>' . $LDSi . '&nbsp;';

				 }

				if($valores[$i]=='No'){	
		
                                $opt .= '<input type="' . $t . '" name="' . $temp['nombre'] . '" value="' . $valores[$i] . '"' . $check .' ' . $disabled . '>No &nbsp;';

				 }

				if($valores[$i]=='Ignorado'){	
		
                                $opt .= '<input type="' . $t . '" name="' . $temp['nombre'] . '" value="' . $valores[$i] . '"' . $check .' ' . $disabled . '>' . $LDIgnorado. '&nbsp;';

				 }


                            }
                        }
                        else if (!strcmp($t, 'select'))
                        {
                            $opt .= '<select name="' . $temp['nombre'] . '" ' . $disabled . '>';
                            for ($i=1;$i<count($valores);$i++)
                            {
                                if (strlen($temp['valor']) != 0)
                                {
                                    if (!strcmp($temp['valor'], $valores[$i]))
                                    {
                                        $check = 'selected';
                                    }
                                    else
                                    {
                                        $check = '';
                                    }
                                }
                                else if (($valores[$i] == "Ignorado") || ($valores[$i] == 'No explorado'))
                                {
                                    $check = 'selected';
                                }

                                if($valores[$i]=='Bueno'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDBueno.'</option>';
                                   			 }
                                else if($valores[$i]=='Regular'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDRegular.'</option>';
                                   			 }
                                else if($valores[$i]=='Deficiente'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDDeficiente.'</option>';
                                   			 }
                                else if($valores[$i]=='Desnutrido'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDDesnutrido.'</option>';
                                   			 }
				else if($valores[$i]=='Nutrido'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDNutrido.'</option>';
                                   			 }
				else if($valores[$i]=='Sobrepeso'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDSobrepeso.'</option>';
                                   			 }
				else if($valores[$i]=='Obesidad'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDobesidad.'</option>';
                                   			 }
				else if($valores[$i]=='Ignorado'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDIgnorado.'</option>';
                                   			 }
				else if($valores[$i]=='No explorado'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDNoExplorado.'</option>';
                                   			 }
				else if($valores[$i]=='Sano'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDSano.'</option>';
                                   			 }
				else if($valores[$i]=='Patologico'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDPatologico.'</option>';
                                   			 }
				else if($valores[$i]=='Si'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$LDSi.'</option>';
                                   			 }
				else if($valores[$i]=='No'){
						 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>No</option>';
                                   			 }
                                //un numero o simbolo
                                else {
                                                 $opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$valores[$i].'</option>';
                                }

                                //$opt .= '<option value="'. $valores[$i] .'" ' . $check .'>'.$valores[$i].'</option>';
                                   								
                            }

                            $opt .= '</select>';
                        } 
                        else if (strstr($t, "date"))
                        {
			//echo "<!-- PRUEBA -->";
			//include_once('../../include/inc_date_format_functions.php');
			//require_once ('../../js/jscalendar/calendar.php');
			//$calendar = new DHTML_Calendar('../../js/jscalendar/', ''.$lang.'', 'calendar-system', true);
			//$calendar->load_files();
                            if (strlen($temp['valor']))
                            {
			      if ($readonly) {
				$opt .= "<input type='text' disabled value='" . $temp['valor'] ."'/>";
			      } else {
                                $opt .=$calendar->show_calendar($calendar,'dd/MM/yyyy', $temp['nombre'],$temp['valor']);
			      }
                            }
                            else if (!strcmp($t, "nodate"))
                            {
                                $opt .=$calendar->show_calendar($calendar,'dd/MM/yyyy', $temp['nombre'],"");
                            }
                            else
                            {
                                $opt .=$calendar->show_calendar($calendar,'dd/MM/yyyy', $temp['nombre'],date("d/m/Y"));
                            }
			}
                        else if (!strcmp($t, 'textarea'))
                        {
                            $opt .= '<textarea name="' . $temp['nombre'] . '" cols="22" onkeydown="return checklength(this);" ' . $disabled . '>'.$temp->fields['valor'].'</textarea>';
                        }
                        else if (strstr($t, 'num'))
                        {
                            if (!strcmp($t, 'textnum'))
                            {
                                if (strlen($temp['valor']) != 0)
                                {
                                    $val = $temp['valor'];
                                }
                                else
                                {
                                    if (strstr($temp['nombre'], "edad"))
                                    {
                                        $person = new Person();
                                        $val = $person->birthday($pid);
                                    }
                                    else
                                    {
                                        $val = 0;
                                    }
                                }
                            }
                            $opt .= '<input type="' . $t . '" name="' . $temp['nombre'] . '" value="' . $val . '" onblur="return checknum(this);" maxlength="15" ' . $disabled . '>';
                        }
                        else
                        {
                            $opt .= '<input type="' . $t . '" name="' . $temp['nombre'] . '" value="' . $temp['valor'] . '" maxlength="25" ' . $disabled . '>';
                        }
                    }

                return $opt . '</td></tr>' . $trup;
        }

        function loadCampos($ficha)
        {
            global $db;

           //$this->sql="SELECT nombre FROM $this->tb_guihistory WHERE ficha='$ficha'";
//         echo $this->sql;
           $salida=$db->GuiSelect(array('nombre'),array('ficha'=>$ficha),$this->tb_guihistory);
           
           /*if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow())
                    {
                        $this->history[] = $temp['nombre'];
                    }
                }
            }*/
            foreach($salida as $temp){
                $this->history[] = $temp['nombre'];
            }
        }

        /*FUNCION NUNCA UTILIZADA*/
        function loadFichas()
        {
            global $db;

            /*$this->sql="SELECT DISTINCT ficha FROM $this->tb_guihistory";
            //echo $this->sql;
            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow())
                    {
                        $out[] = $temp['ficha'];
                    }
                }
            }*/
            
            $salida=$db->GuiSelect(array('DISTINCT ficha'),NULL,$this->tb_guihistory);
           if($salida)
           {
               foreach($salida as $temp)
               {
               $out[] = $temp['ficha'];
               }

            }
            return $out;
        }

        function loadFichasInsertadas($pid, $ficha)
        {
            global $db;

            /*$sel = '';
            if (!strcmp('antecedentes', $ficha))
            {
                $sel = ',id_correlativo ';
            }

            $this->sql="SELECT id_campo$sel FROM $this->tb_historydata WHERE ficha='$ficha' and id_paciente='$pid'";
            //echo $this->sql;
            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow())
                    {
                        $out[] = $temp['id_campo'];
			if (!strcmp('antecedentes', $ficha))
			{
				$this->correlativo=$temp['id_correlativo'];
			}
                    }
                }
            }*/
            $seleccion=array('id_campo');
            if (!strcmp('antecedentes', $ficha))
            {
                $seleccion[] = 'id_correlativo';
            }
            $salida=$db->GuiSelect($seleccion,array('ficha'=>$ficha,'id_paciente'=>$pid),$this->tb_historydata);
            foreach($salida as $temp){
                $out[] = $temp['id_campo'];
                    if (!strcmp('antecedentes', $ficha))
                    {
			$this->correlativo=$temp['id_correlativo'];
                    }

            }

           return $out;
        }

        function guardarAdjunto($fileInput, $id){
		global $db;

		if($fileInput!=''){
			$file = fopen('/tmp/'.$fileInput,"r");
			
			while(!feof($file)){
				$imgData .= fread($file, 1024);
			}
	
			$size=filesize('/tmp/'.$fileInput);
	
			fclose($file); 
			
			$imgData = addslashes ($imgData);
			$imgData = addcslashes($imgData, "\0"); 
	
			//$this->sql = "INSERT INTO $this->tb_adjunto (name,size,content,id_soap) VALUES ('$fileInput', $size, '$imgData',$id)";
			//$this->Transact();
                        $result= $db->transact("",array("name"=>$fileInput,"size"=>$size,"content"=>$imgData,"id_soap"=>$id),"Insert",$this->tb_adjunto);
                        //return$result;
		}

	}

        function guardarAdjuntoSOAP($fileInput, $id){
		global $db;

		if($fileInput!=''){
			$file = fopen('/tmp/'.$fileInput,"r");
			
			while(!feof($file)){
				$imgData .= fread($file, 1024);
			}
	
			$size=filesize('/tmp/'.$fileInput);
	
			fclose($file); 
			
			$imgData = addslashes ($imgData);
			$imgData = addcslashes($imgData, "\0"); 
	
			//$this->sql = "INSERT INTO $this->tb_adjunto (name,size,content,id_soap) VALUES ('$fileInput', $size, '$imgData',$id)";
			//$this->Transact();
                        $result= $db->transact("",array("name"=>$fileInput,"size"=>$size,"content"=>$imgData,"id_soap"=>$id),"Insert",$this->tb_adjunto);
                        //return$result;
		}

	}

        function seleccionarNombreAdjuntos($id){
		global $db;

		/*$this->sql = "SELECT name FROM $this->tb_adjunto WHERE id_soap=".$id;

 		echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}
		}*/
                $salida=$db->GuiSelect(array('name'),array('id_soap'=>$id),$this->tb_adjunto);
                if($salida) {
			foreach ($salida as $temp ){

				$result[]=$temp;


			}
                        return $result;
		}
		else {
		return false;
		}

	}
}
?>
